package client.ui;

import client.network.BanchoClient;
import common.Callback;
import common.database.User;
import common.enums.EndpointType;
import common.enums.RequestType;
import common.requests.Request;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.input.MouseButton;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.Pane;
import javafx.scene.text.Text;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.*;


public class primaryUIController implements Initializable, ControlledStage, Callback{
    stageController theStageController;                //舞台控制器

    @FXML public TreeView<String> friendsList;
    List<Contacts> contacts = Arrays.asList(
            // new Contacts("张三","我的好友"),
            new Contacts("王五","家人"),
            new Contacts("廖六","朋友"),
            new Contacts("陈八","同学"));
    ArrayList<TreeItem<String>> groupTypeNodeList;
    //必须设置一个根节点
    TreeItem<String> rootNode = new TreeItem("分组管理");
    @FXML public Button addFriends = new Button();


    @FXML public TreeView<String> groupsTalkList;
    TreeItem<String> rootNode1 = new TreeItem("群管理");
    @FXML public Button addGroup = new Button();

    @FXML public Text nameText;

    /*----------------------------------------------实现接口函数----------------------------------------*/
    public void setStageController(stageController stageController){
        theStageController = stageController;
    }

    /*-------------------------------------------------初始化----------------------------------------------*/
    public void initialize(URL location, ResourceBundle resources) {
        BanchoClient.addCallback(this);

        /*----------------------------好友--------------------------------*/
        rootNode.setExpanded(true);
        //创建联系人分组
        ArrayList<TreeItem<String>> groupTypeNodeList = new ArrayList<TreeItem<String>>();
        groupTypeNodeList.add(new TreeItem<>("我的好友"));
        groupTypeNodeList.add(new TreeItem<>("家人"));
        groupTypeNodeList.add(new TreeItem<>("朋友"));
        groupTypeNodeList.add(new TreeItem<>("同学"));

        //根据根节点添加初始分组元素
        for (int i = 0; i < 4; i++) {
            rootNode.getChildren().add(groupTypeNodeList.get(i));
        }

        //给对应分组添加成员
        for (Contacts c : contacts) {                                  //对于每个
            TreeItem<String> peopleLeaf = new TreeItem(c.getPeople());    //设置具体人 Item
            for (TreeItem<String> g : groupTypeNodeList) {
                if (g.getValue().contentEquals(c.getGroupType())) {
                    g.getChildren().add(peopleLeaf);
                }
            }
        }
        friendsList.setRoot(rootNode);
        friendsList.setEditable(true);

        //鼠标事件
        friendsList.setOnMouseClicked((MouseEvent event) -> {
            //鼠标右击事件
            if (event.getButton() == MouseButton.SECONDARY) {
                if (friendsList.getSelectionModel().getSelectedItem() == null) {
                    return;
                }

                //变更和删除好友分组
                if (friendsList.getSelectionModel().getSelectedItem().isLeaf() && friendsList.getSelectionModel().getSelectedItem().getParent() != rootNode) {
                    final ContextMenu changeMenu = new ContextMenu();
                    MenuItem changePos = new MenuItem("变更分组");
                    MenuItem deletePeople = new MenuItem("删除好友");
                    changeMenu.getItems().add(changePos);
                    changeMenu.getItems().add(deletePeople);
                    friendsList.setContextMenu(changeMenu);

                    changePos.setOnAction((ActionEvent t) -> {
                        String nameToMove = friendsList.getSelectionModel().getSelectedItem().getValue();    //要移动的成员
                        ChoiceDialog<String> aimGroup = new ChoiceDialog();
                        aimGroup.setTitle("变更分组");
                        aimGroup.setHeaderText("");
                        aimGroup.setContentText("更改为分组：");

                        for (int i = 0; i < rootNode.getChildren().size(); i++) {
                            aimGroup.getItems().add(rootNode.getChildren().get(i).getValue());
                        }

                        aimGroup.showAndWait();

                        for (int i = 0; i < rootNode.getChildren().size(); i++) {
                            if (rootNode.getChildren().get(i).getValue() == aimGroup.getSelectedItem()) {
                                rootNode.getChildren().get(i).getChildren().add(new TreeItem<>(nameToMove));
                                //删除当前位置
                                friendsList.getSelectionModel().getSelectedItem().getParent().getChildren().remove(friendsList.getSelectionModel().getSelectedItem());
                                break;
                            }
                        }
                    });

                    deletePeople.setOnAction((ActionEvent t) -> {
                        friendsList.getSelectionModel().getSelectedItem().getParent().getChildren().remove(friendsList.getSelectionModel().getSelectedItem());
                    });
                    return;
                } else {
                    friendsList.setContextMenu(null);
                }

                if (friendsList.getSelectionModel().getSelectedItem().getParent() == rootNode) {
                    final ContextMenu addMenu = new ContextMenu();
                    MenuItem addMenuItem = new MenuItem("增加分组");
                    MenuItem deleteMenuItem = new MenuItem("删除分组");
                    addMenu.getItems().add(addMenuItem);
                    addMenu.getItems().add(deleteMenuItem);
                    friendsList.setContextMenu(addMenu);

                    //选择"增加分组"
                    addMenuItem.setOnAction((ActionEvent t) -> {
                        TextInputDialog text = new TextInputDialog();
                        text.setTitle("新建分组");
                        text.setHeaderText("");
                        text.setContentText("新建分组名：");
                        text.showAndWait();      //代码在此处停住

                        String newGroup = text.getEditor().getText();

                        if (newGroup != "") {
                            TreeItem newEmployee = new TreeItem(newGroup);
                            rootNode.getChildren().add(newEmployee);
                        }
                    });

                    //选择"删除分组"
                    deleteMenuItem.setOnAction((ActionEvent t) -> {
                        //删除当前分组
                        //定位到目前的分组
                        if (friendsList.getSelectionModel().getSelectedItem().getValue() == "我的好友") return;
                        else {
                            rootNode.getChildren().get(0).getChildren().addAll(friendsList.getSelectionModel().getSelectedItem().getChildren());
                            rootNode.getChildren().remove(friendsList.getSelectionModel().getSelectedItem());
                        }
                    });
                }
            }

            //双击listView增加好友列表
            if (event.getClickCount() == 2) {
                if (friendsList.getSelectionModel().getSelectedItem().getParent() != rootNode && friendsList.getSelectionModel().getSelectedItem().isLeaf()) {
                    String nikeName = friendsList.getSelectionModel().getSelectedItem().getValue();
                    //通过NikeName得到聊天人的ID

                    FXMLLoader loading = new FXMLLoader(getClass().getResource("/ui/textUI.fxml"));
                    Pane tempPane = null;
                    try {
                        tempPane = loading.load();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    ((textUIControlller) loading.getController()).setUid(Long.parseLong(nikeName.split(":")[0]));
                    ((textUIControlller) loading.getController()).setUsername(nikeName.split(":")[1]);
                    Scene tempScene = new Scene(tempPane);
                    Stage tempStage = new Stage();
                    tempStage.setResizable(false);
                    tempStage.setScene(tempScene);

                    tempStage.show();
                }
            }
        });

        /*---------------------------------群---------------------------*/
        rootNode1.setExpanded(true);
        groupsTalkList.setRoot(rootNode1);
        nameText.setText(BanchoClient.user.username);
        //鼠标事件
        groupsTalkList.setOnMouseClicked((MouseEvent event) -> {
            if (event.getButton() == MouseButton.SECONDARY) {
                //退群
                final ContextMenu groupMenu = new ContextMenu();
                MenuItem backGroup = new MenuItem("退出该群");
                MenuItem createGroup = new MenuItem("创建群");
                groupMenu.getItems().add(backGroup);
                groupMenu.getItems().add(createGroup);
                groupsTalkList.setContextMenu(groupMenu);

                backGroup.setOnAction((ActionEvent t) -> {
                    //服务器端退出该群
                    groupsTalkList.getSelectionModel().getSelectedItem().getParent().getChildren().remove(groupsTalkList.getSelectionModel().getSelectedItem());
                });

                createGroup.setOnAction((ActionEvent t) -> {
                    //创建群
                    TextInputDialog groupName = new TextInputDialog();
                    groupName.setTitle("创建新群");
                    groupName.setHeaderText("");
                    groupName.setContentText("群名：");
                    groupName.showAndWait();

                    Map<String, Object> map = new HashMap<>();
                    map.put("name", groupName.getEditor().getText());
                    BanchoClient.SendRequest(RequestType.Group_Create, map);

                });
            }

            if (event.getClickCount() == 2 && groupsTalkList.getSelectionModel().getSelectedItem().getParent() == rootNode1) {
                //进入群界面
                if (groupsTalkList.getSelectionModel().getSelectedItem().getValue() != "你还没有任何群") {
                    String groupName = groupsTalkList.getSelectionModel().getSelectedItem().getValue();
                    //通过groupName得到聊天群的ID

                    FXMLLoader loading = new FXMLLoader(getClass().getResource("/ui/textUI.fxml"));
                    Pane tempPane = null;
                    try {
                        tempPane = loading.load();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    Scene tempScene = new Scene(tempPane);
                    Stage tempStage = new Stage();
                    tempStage.setResizable(false);
                    tempStage.setScene(tempScene);
                    ((textUIControlller)loading.getController()).setUid(Long.parseLong(groupName.split(":")[0]));
                    ((textUIControlller)loading.getController()).setEndpointType(EndpointType.Group);
                    ((textUIControlller)loading.getController()).setUsername(groupName.split(":")[1]);
                    tempStage.show();
                }
            }
        });
    }


    /*------------------------------------------------三个Button-------------------------------------------*/
    @FXML
    public void addGroupButton(){
        TextInputDialog groupNumber = new TextInputDialog();
        groupNumber.setTitle("加入群");
        groupNumber.setHeaderText("");
        groupNumber.setContentText("请输入群号：");
        groupNumber.showAndWait();

        String gNumber = groupNumber.getEditor().getText();
        //将gNumber发送给服务器
        Map<String, Object> map = new HashMap<>();
        map.put("id", Long.valueOf(gNumber));
        BanchoClient.SendRequest(RequestType.Group_RequestJoin, map);
    }


    long ID = 11111;
    @FXML
    public void addFriends(){
        TextInputDialog friendID = new TextInputDialog();
        friendID.setTitle("加好友");
        friendID.setHeaderText("");
        friendID.setContentText("好友ID：");
        friendID.showAndWait();
        //long转String
        ID = Integer.parseInt(friendID.getEditor().getText());
        Map<String, Object> map = new HashMap<>();
        map.put("user", ID);
        BanchoClient.SendRequest(RequestType.Friend_Add, map);
    }

    /*---------------------------------------------------网络回馈-------------------------------------------*/

    @Override
    public void callback(Request request) {
        Platform.runLater(() -> {
            if (request.type == RequestType.Friend_GetList) {
                List<Map<String, Object>> list = (List<Map<String, Object>>)request.payload.get("friends");
                rootNode.getChildren().get(0).getChildren().removeAll();
                for (int i = 0; i < list.size(); i++){
                    rootNode.getChildren().get(0).getChildren().add(new TreeItem<>(list.get(i).get("id") + ":" + list.get(i).get("username")));
                }
            }
            if (request.type == RequestType.Group_List) {
                List<Map<String, Object>> list = (List<Map<String, Object>>)request.payload.get("groups");
                rootNode1.getChildren().removeAll();
                for (int i = 0; i < list.size(); i++){
                    rootNode1.getChildren().add(new TreeItem<>(list.get(i).get("id") + ":" + list.get(i).get("name")));
                }
            }
        });
    }


    //联系人的类
    public static class Contacts {
            private final SimpleStringProperty groupType;    //分组
            private final SimpleStringProperty people;        //其中的人

            private Contacts(String people, String groupType) {
                this.people = new SimpleStringProperty(people);
                this.groupType = new SimpleStringProperty(groupType);
            }
            public String getPeople() {
                return people.get();
            }
            public void setName(String peopleName) {
                people.set(peopleName);
            }
            public String getGroupType() {
                return groupType.get();
            }
            public void setDepartment(String groupTypeName) {
                groupType.set(groupTypeName);
            }
    }
}
